package threadsafe;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by 5406160@qq.com on LiBoWen 李博闻.
 *
 * @ClassName : SellTicket3
 * @Author : 54061
 * @Date: 2022/2/15 18:22
 */
public class SellTicket3 implements Runnable{
    //总票数 : 共享数据
    int ticket = 100;
    //共享的lock对象
    Lock lock = new ReentrantLock();

    @Override
    public void run() {
        //火车站不关门
        while (true){
            //上锁
            lock.lock();
            //判断
            if (ticket>0){
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //买票
                System.out.println(Thread.currentThread().getName()+"买了第"+ticket+"张票");
                //真正的买票
                ticket--;
            }
            //解锁
            lock.unlock();
        }

    }
}
